package game.module.mj.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.mj.bean.MjRoom;
import game.module.mj.logic.MjDataManager;
import game.session.SessionManager;
import io.netty.buffer.ByteBuf;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageMj.C2SMjVoicePlay;
import lua.LuaMessageMj.PushMjVoicePlay;
import lua.LuaMessageMj.S2CMjVoicePlay;
import lua.LuaMessageNn.C2SNnVoicePlay;

@MsgCodeAnn(msgcode = C2SMjVoicePlay.id, accessLimit = 500)
public class MjVoicPlayProcessor extends PlayingRoleMsgProcessor{

	private static Logger logger = LoggerFactory.getLogger(MjVoicPlayProcessor.class);
	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {
		// TODO Auto-generated method stub
		C2SNnVoicePlay reqMsg = C2SNnVoicePlay.parse(requestMessage);
		ByteBuf voice_content = reqMsg.content;
		int playerId = playingRole.getId();
		logger.info("Mj voice play,playeyId={}", playerId);
		// 是否在房间中
		boolean isInRoom = MjDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// is room exist
		final MjRoom ddzRoom = MjDataManager.getInstance().getMjRoomByPlayerId(playerId);
		if (ddzRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 发送
		S2CMjVoicePlay respMsg = new S2CMjVoicePlay();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		// 推送
		List<Integer> playerIdList = ddzRoom.getPlayerList();
		PushMjVoicePlay pushMessage = new PushMjVoicePlay();
		pushMessage.player_index = (byte) playerIdList.indexOf(playerId);
		pushMessage.content = voice_content;
		for (Integer aPlayerId : playerIdList) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMessage.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
